<template>
  <s-layout title="确认订单">
    <view
      class="bg-white address-box ss-m-b-14 ss-r-b-20"
      @tap="onSelectAddress"
      v-if="state.orderInfo.need_address === 1"
    >
      <s-address-item :item="state.addressInfo" :hasBorderBottom="false">
        <view class="ss-rest-button"><text class="_icon-forward"></text></view>
      </s-address-item>
    </view>
    <view class="order-card-box ss-m-b-14">
      <s-goods-item
        v-for="item in state.orderInfo.goods_list"
        :key="item.goods_id"
        :img="item.current_sku_price.image || item.goods.image"
        :title="item.goods.title"
        :skuText="item.current_sku_price?.goods_sku_text"
        :price="item.current_sku_price.price"
        :num="item.goods_num"
        marginBottom="10"
      >
        <template #top>
          <view class="order-item ss-flex ss-col-center ss-row-between ss-p-x-20 bg-white">
            <view class="item-title">配送方式</view>
            <view class="ss-flex ss-col-center">
              <text class="item-value">{{ item.dispatch_type_text }}</text>
            </view>
          </view>
        </template>
      </s-goods-item>

      <view class="order-item ss-flex ss-col-center ss-row-between ss-p-x-20 bg-white ss-r-20">
        <view class="item-title">订单备注</view>
        <view class="ss-flex ss-col-center">
          <uni-easyinput
            maxlength="20"
            placeholder="建议留言前先与商家沟通"
            v-model="state.orderPayload.remark"
            :inputBorder="false"
            :clearable="false"
          ></uni-easyinput>
        </view>
      </view>
    </view>
    <!-- 合计 -->
    <view class="bg-white total-card-box ss-p-20 ss-m-b-14 ss-r-20">
      <view class="total-box-content border-bottom">
        <view class="order-item ss-flex ss-col-center ss-row-between">
          <view class="item-title">商品金额</view>
          <view class="ss-flex ss-col-center">
            <text class="item-value ss-m-r-24">￥{{ state.orderInfo.goods_amount }}</text>
          </view>
        </view>
        <view
          class="order-item ss-flex ss-col-center ss-row-between"
          v-if="state.orderPayload.order_type === 'score'"
        >
          <view class="item-title">扣除积分</view>
          <view class="ss-flex ss-col-center">
            <image
              :src="sheep.$url.static('/assets/addons/shopro/uniapp/goods/score1.svg')"
              class="score-img"
            ></image>
            <text class="item-value ss-m-r-24">{{ state.orderInfo.score_amount }}</text>
          </view>
        </view>
        <view class="order-item ss-flex ss-col-center ss-row-between">
          <view class="item-title">运费</view>
          <view class="ss-flex ss-col-center">
            <text class="item-value ss-m-r-24">+￥{{ state.orderInfo.dispatch_amount }}</text>
          </view>
        </view>
        <view
          class="order-item ss-flex ss-col-center ss-row-between"
          v-if="state.orderPayload.order_type != 'score'"
        >
          <!-- <view v-if="state.orderInfo.coupon_discount_fee > 0" class="order-item ss-flex ss-col-center ss-row-between"> -->
          <view class="item-title">优惠券</view>
          <view class="ss-flex ss-col-center" @tap="state.showCoupon = true">
            <text class="item-value text-red" v-if="state.orderPayload.coupon_id"
              >-￥{{ state.orderInfo.coupon_discount_fee }}</text
            >
            <text
              class="item-value"
              :class="state.couponInfo.can_use?.length > 0 ? 'text-red' : 'text-disabled'"
              v-else
              >{{
                state.couponInfo.can_use?.length > 0
                  ? state.couponInfo.can_use?.length + '张可用'
                  : '暂无可用优惠券'
              }}</text
            >

            <text class="_icon-forward item-icon"></text>
          </view>
        </view>
        <view
          class="order-item ss-flex ss-col-center ss-row-between"
          v-if="state.orderInfo.promo_infos?.length"
        >
          <!-- <view v-if="state.orderInfo.promo_discount_fee > 0" class="order-item ss-flex ss-col-center ss-row-between"> -->
          <view class="item-title">活动优惠</view>
          <view class="ss-flex ss-col-center" @tap="state.showDiscount = true">
            <text class="item-value text-red"> -￥{{ state.orderInfo.promo_discount_fee }} </text>
            <text class="_icon-forward item-icon"></text>
          </view>
        </view>
      </view>
      <view class="total-box-footer ss-font-28 ss-flex ss-row-right ss-col-center ss-m-r-28">
        <view class="total-num ss-m-r-20">共{{ state.totalNumber }}件</view>
        <view>合计：</view>
        <view class="total-num text-red"> ￥{{ state.orderInfo.pay_fee }} </view>
        <view class="ss-flex" v-if="state.orderPayload.order_type === 'score'">
          <view class="total-num ss-font-30 text-red ss-m-l-4"> + </view>
          <image
            :src="sheep.$url.static('/assets/addons/shopro/uniapp/goods/score1.svg')"
            class="score-img"
          ></image>
          <view class="total-num ss-font-30 text-red">{{ state.orderInfo.score_amount }}</view>
        </view>
      </view>
    </view>
    <!-- 发票 -->
    <view class="bg-white ss-p-20 ss-r-20">
      <view class="order-item ss-flex ss-col-center ss-row-between">
        <view class="item-title">发票申请</view>
        <view class="ss-flex ss-col-center" @tap="onSelectInvoice">
          <text class="item-value">{{ state.invoiceInfo.name || '无需开具发票' }}</text>
          <text class="_icon-forward item-icon"></text>
        </view>
      </view>
    </view>
    <!-- 选择优惠券弹框 -->
    <s-coupon-select
      v-model="state.couponInfo"
      :show="state.showCoupon"
      @confirm="onSelectCoupon"
      @close="state.showCoupon = false"
    />
    <!-- 满额折扣弹框  -->
    <s-discount-list
      v-model="state.orderInfo"
      :show="state.showDiscount"
      @close="state.showDiscount = false"
    />
	
	<su-popup
	  :show="state.showModal"
	  type="center"
	  round="20"
	  :showClose="false"
	  :isMaskClick="false"
	>
	  <view class="ss-p-x-20 ss-p-y-30 content-box">
	    <view class="model-title ss-m-b-30 ss-m-l-20">外卖合伙人合作协议</view>
	    <scroll-view class="input-box ss-m-b-70" scroll-y="true">
		
			甲方:成都红瑞聚宝科技有限公司统一社会信用代码: 91510100MA62NB2C60地址: 中国（四川）自由贸易试验区成都高新区府城大道中段88号1栋7层2号<br/>
			<view style="margin-top: 20rpx;">乙方:同意协议自动同步注册信息</view>
			甲方将发起并设立一家有限合伙企业，由甲方担任普通合伙人，乙方作为意向投资人，同意在将来担任有限合伙人，现双方协商一致，根据《中华人民共和国民法典》等相关法律法规的规定，特达成如下协议，以兹遵守:<br/>
			<view class="title-h2">一、有限合伙企业的基本模式</view>
			1、有限合伙企业合伙人共计14人，其中普通合伙人1人，由甲方担任，有限合伙人13人，由乙方及其他投资人担任。<br/>
			2、有限合伙企业主营业务方向为:销售外卖餐饮、蛋糕、果茶(具体以“合伙协议”或工商登记备案载明内容为准)<br/>
			3、收银系统采用甲方公司APP、小程序，有限合伙企业成立后，由有限合伙企业向甲方购买使用权。<br/>
			4、经营期间由甲方负责全权经营，乙方不参与经营，仅分取收益。但自本合同生效后，作为合伙人，乙方有责任和义务为“外卖合伙人”事业进行营销及宣传。<br/>
			<view class="title-h2">二、开办费用</view>
			1、待有限合伙人人数满足14人之条件时，由甲方就经营店铺进行选址。<br/>
			2、店铺装饰装修风格按甲方的要求进行。<br/>
			3、店铺内所有设施设备按甲方要求采购。<br/>
			4、所选店铺位置乙方有权提出建议。<br/>
			<view class="title-h2">三、出资方式</view>
			1、甲方以“外卖合伙人”商业模式、劳务、其他权利等作价进行出资，占有限合伙企业份额的47%。<br/>
			2、乙方以现金出资，占有限合伙企业份额的4%。<br/>
			3、有限合伙企业注册资本金、全体合伙人出资方式、所占份额等最终以《合伙协议》约定为准。<br/>
			<view class="title-h2">四、分红及亏损负担</view>
			1、甲乙方共同承担亏损风险，乙方按营业收入比例分取利益，如有限合伙企业出现亏损，由甲乙双方协商闭店或则换品。	<br/>
			2、乙方分红根据店铺实际盈利，店铺营业额百分之10到百分之20之间。<br/>
			<view class="title-h2">五、争议解决</view>
			因履行本合同产生的争议，均由甲方所在地人民法院管辖，甲方注册地址变更的，以变更后的地址为准。<br/>
			<view class="title-h2">六、特别约定</view>
			1、本协议系乙方单独的合作协议，乙方清楚并明白有限合伙企业的成立需一共达到13个合伙人(甲方为普通合伙人，包括乙方在内的其余14个投资人)才能成立。有关成立有限合伙企业具体内容以甲方、乙方与其他13个投资人共同签署的《合伙协议》为准，《合伙协议》与本协议不一致的，以《合伙协议》为准。<br/>
			2、乙方不得侵犯甲方的知识产权或模仿/抄袭甲方商业模式、泄露甲方商业秘密，除与甲方合伙经营“外卖合伙人”门店以外，乙方不得以任何形式与甲方进行同业竞争(包括但不限于乙方在连锁卤味、蛋糕、饮品行业自营或与他人合营或任职于与甲方相同或类似行业的公司)。乙方认可该等行为属于不正当竞争行为，若违反该条约定，乙方需按其总投资金额的10倍向甲方支付违约金，若违约金不足以弥补甲方实际损失的，乙方还需补充赔偿至甲方实际损失。<br/>
			<view class="title-h2">七、本协议效力</view>
			1、本协议自双方签字或盖章当日生效。<br/>
			2、本协议未尽事宜，双方可达成补充协议，补充协议与本协议具有同等法律效力。<br/>
		
	    </scroll-view>
		
		<button
		  class="ss-reset-button model-btn bg-grey"
		  v-if="state.second_num > 0"
		>
		  我同意({{state.second_num}}秒)
		</button>
		
	    <button
	      class="ss-reset-button model-btn ui-BG-Main-Gradient ui-Shadow-Main"
	      @tap="state.showModal = false"
		  v-if="state.second_num <= 0"
	    >
	      我同意
	    </button>
	  </view>
	</su-popup>
	
	
    <!-- 底部 -->
    <su-fixed bottom :opacity="false" bg="bg-white" placeholder :noFixed="false" :index="200">
      <view class="footer-box border-top ss-flex ss-row-between ss-p-x-20 ss-col-center">
        <view class="total-box-footer ss-flex ss-col-center">
          <view class="total-num ss-font-30 text-red"> ￥{{ state.orderInfo.pay_fee }} </view>
          <view v-if="state.orderPayload.order_type === 'score'" class="ss-flex">
            <view class="total-num ss-font-30 text-red ss-m-l-4">+</view>
            <image
              :src="sheep.$url.static('/assets/addons/shopro/uniapp/goods/score1.svg')"
              class="score-img"
            ></image>
            <view class="total-num ss-font-30 text-red">{{ state.orderInfo.score_amount }}</view>
          </view>
        </view>
			
        <button
          class="ss-reset-button ui-BG-Main-Gradient ss-r-40 submit-btn ui-Shadow-Main"
          @tap="onConfirm"
        >
          {{ exchangeNow ? '立即兑换' : '提交订单' }}
        </button>
      </view>
    </su-fixed>
	
  </s-layout>
</template>

<script setup>
  import { reactive, computed } from 'vue';
  import { onLoad, onPageScroll, onShow } from '@dcloudio/uni-app';
  import sheep from '@/sheep';
  import { isEmpty } from 'lodash';

  const state = reactive({
    orderPayload: {},
    orderInfo: {},
    addressInfo: {},
    invoiceInfo: {},
    totalNumber: 0,
    showCoupon: false,
    couponInfo: [],
    showDiscount: false,
	second_num: 0,
	showModal:false,
	clearSetInterval:null,
  });

  //定时让用户协议弹窗弹出
  setTimeout(function(){
	  state.second_num = 5;
	  state.showModal = true;
  }, 500);
  
  state.clearSetInterval = setInterval(function (){
	 if(state.second_num-1 >= 0){
		 state.second_num--; 
	 }else{
		state.clearSetInterval = null;
	 }
  }, 1000);


  // 立即兑换(立即兑换无需跳转收银台)
  const exchangeNow = computed(
    () => state.orderPayload.order_type === 'score' && state.orderInfo.pay_fee == 0,
  );

  // 选择地址
  function onSelectAddress() {
    uni.$once('SELECT_ADDRESS', (e) => {
      changeConsignee(e.addressInfo);
    });
    sheep.$router.go('/pages/user/address/list');
  }

  // 更改收货人地址&计算订单信息
  async function changeConsignee(addressInfo = {}) {
    if (isEmpty(addressInfo)) {
      const { code, data } = await sheep.$api.user.address.default();
      if (code === 1 && !isEmpty(data)) {
        addressInfo = data;
      }
    }
    if (!isEmpty(addressInfo)) {
      state.addressInfo = addressInfo;
      state.orderPayload.address_id = state.addressInfo.id;
    }
    getOrderInfo();
  }

  // 选择优惠券
  async function onSelectCoupon(e) {
    state.orderPayload.coupon_id = e || 0;
    getOrderInfo();
    state.showCoupon = false;
  }

  // 选择发票信息
  function onSelectInvoice() {
    uni.$once('SELECT_INVOICE', (e) => {
      state.invoiceInfo = e.invoiceInfo;
      state.orderPayload.invoice_id = e.invoiceInfo.id || 0;
    });
    sheep.$router.go('/pages/user/invoice/list');
  }

  // 提交订单/立即兑换
  function onConfirm() {
    if (!state.orderPayload.address_id && state.orderInfo.need_address === 1) {
      sheep.$helper.toast('请选择收货地址');
      return;
    }

    if (exchangeNow.value) {
      uni.showModal({
        title: '提示',
        content: '确定使用积分立即兑换?',
        cancelText: '再想想',
        success: async function (res) {
          if (res.confirm) {
            submitOrder();
          }
        },
      });
    } else {
      submitOrder();
    }
  }

  // 创建订单&跳转
  async function submitOrder() {
    const { code, data } = await sheep.$api.order.create(state.orderPayload);
    if (code === 1) {
      // 更新购物车列表
      if (state.orderPayload.from === 'cart') {
        sheep.$store('cart').getList();
      }
      if (data.status === 'paid') {
        sheep.$router.redirect('/pages/pay/result', {
          orderSN: data.order_sn,
        });
      } else {
        sheep.$router.redirect('/pages/pay/index', {
          orderSN: data.order_sn,
        });
      }
    }
  }

  // 检查库存&计算订单价格
  async function getOrderInfo() {
    let { code, data } = await sheep.$api.order.calc(state.orderPayload);
    if (code === 1) {
      state.totalNumber = 0;
      state.orderInfo = data;
      state.orderInfo.goods_list.forEach((item) => {
        state.totalNumber += item.goods_num;
      });
    }
  }

  // 获取可用优惠券
  async function getCoupons() {
    const { code, data } = await sheep.$api.order.coupons(state.orderPayload);
    if (code === 1) {
      state.couponInfo = data;
    }
  }

  onLoad(async (options) => {
    if (options.data) {
      state.orderPayload = JSON.parse(options.data);
      changeConsignee();
      if (state.orderPayload.order_type !== 'score') {
        getCoupons();
      }
    }
  });
</script>

<style lang="scss" scoped>
  :deep() {
    .uni-input-wrapper {
      width: 320rpx;
    }

    .uni-easyinput__content-input {
      font-size: 28rpx;
      height: 72rpx;
      text-align: right !important;
      padding-right: 0 !important;

      .uni-input-input {
        font-weight: 500;
        color: #333333;
        font-size: 26rpx;
        height: 32rpx;
        margin-top: 4rpx;
      }
    }
    .uni-easyinput__content {
      display: flex !important;
      align-items: center !important;
      justify-content: right !important;
    }
  }
  .score-img {
    width: 36rpx;
    height: 36rpx;
    margin: 0 4rpx;
  }
  .order-item {
    height: 80rpx;

    .item-title {
      font-size: 28rpx;
      font-weight: 400;
    }

    .item-value {
      font-size: 28rpx;
      font-weight: 500;
      font-family: OPPOSANS;
    }

    .text-disabled {
      color: #bbbbbb;
    }

    .item-icon {
      color: $dark-9;
    }

    .remark-input {
      text-align: right;
    }

    .item-placeholder {
      color: $dark-9;
      font-size: 26rpx;
      text-align: right;
    }
  }

  .total-box-footer {
    height: 90rpx;

    .total-num {
      color: #333333;
      font-family: OPPOSANS;
    }
  }

  .footer-box {
    height: 100rpx;

    .submit-btn {
      width: 240rpx;
      height: 70rpx;
      font-size: 28rpx;
      font-weight: 500;

      .goto-pay-text {
        line-height: 28rpx;
      }
    }

    .cancel-btn {
      width: 240rpx;
      height: 80rpx;
      font-size: 26rpx;
      background-color: #e5e5e5;
      color: $dark-9;
    }
  }
  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333333;
  }
  .subtitle {
    font-size: 28rpx;
    color: #999999;
  }
  .cicon-checkbox {
    font-size: 36rpx;
    color: var(--ui-BG-Main);
  }
  .cicon-box {
    font-size: 36rpx;
    color: #999999;
  }
  
 
  
  .content-box{
	display:flex;
	align-items: center;
	justify-content: center;
	flex-direction: column;
	padding: 30rpx 30rpx;
  }
  
  .model-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333333;
	margin-bottom: 60rpx;
  }
  
  .input-box{
	  width: 600rpx;
	  height: 650rpx;
	  overflow-y: auto;
  }
  
  .model-btn {
    width: 100%;
    height: 80rpx;
    border-radius: 40rpx;
    font-size: 28rpx;
    font-weight: 500;
    color: #ffffff;
    line-height: normal;
  }
  
  .title-h2{
	  font-weight: 700;
	  margin-top:20rpx;
  }
</style>
